package org.robot.scm.platform.wxrobot.processor;

import com.google.common.collect.Lists;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.robot.scm.pojos.config.BaseConfig;
import org.robot.scm.infra.LocalCacheHelper;
import org.robot.scm.platform.wxrobot.AbstractRobotProcessor;
import org.robot.scm.pojos.TargetNotify;
import org.robot.scm.pojos.config.base.BasePlatform;
import org.robot.scm.pojos.enums.PlatformEnum;
import org.robot.scm.pojos.platform.BeautyBaseNotify;
import org.robot.scm.retry.SimpleRetryable;
import org.robot.scm.utils.DateTool;
import org.robot.scm.utils.JsonHelper;
import org.robot.scm.utils.NetImageTool;
import org.robot.scm.utils.StreamUtils;

/**
 * @Author : Awn create on 2024/4/22 15:52
 */
public class BeautyRobotProcessor extends AbstractRobotProcessor {

    private static final String TAG = BeautyRobotProcessor.class.getSimpleName();

    @Override
    public List<String> getKeywords(BaseConfig config) {
        return config.get().getPlatform(PlatformEnum.BEAUTY).getKeywords();
    }

    @Override
    protected List<TargetNotify> process(BaseConfig config, String sendTo, String msg) {
        return new SimpleRetryable(3, 2000).retry(() -> this.doProcess(config, sendTo), Objects::nonNull);
    }

    private List<TargetNotify> doProcess(BaseConfig config, String sendTo) {
        BasePlatform currentPlatform = config.get().getPlatform(PlatformEnum.BEAUTY);
        List<String> urlTextList = JsonHelper.toList(LocalCacheHelper.get(TAG));
        if (CollectionUtils.isEmpty(urlTextList)) {
            urlTextList.addAll(this.loadAndCache(currentPlatform.getNoticeSrc()));
        }
        this.shuffle(urlTextList);
        String imgUrl = urlTextList.get(0);
        File saveFile = new File(String.format("assets/images/%s.jpg", Math.abs(imgUrl.hashCode())));
        if (!saveFile.exists()) {
            if (!NetImageTool.download(imgUrl, saveFile.getAbsolutePath())) {
                return Lists.newArrayList();
            }
        }
        if (!NetImageTool.download(imgUrl, saveFile.getAbsolutePath())) {
            return null;
        }
        BeautyBaseNotify beautyBean = BeautyBaseNotify.builder()
                .url(saveFile.getAbsolutePath())
                .createHour(DateTool.format(new Date(), DateTool.PATTERN_6))
                .build();
        List<String> filter = StreamUtils.filter(config.get().getRobots(PlatformEnum.BEAUTY), e -> StringUtils.equals(e, sendTo));
        return StreamUtils.convertAndDistinct(filter, e -> beautyBean.robotToNotifyBean(e, config));
    }

    @SneakyThrows
    private List<String> loadAndCache(String noticeSrc) {
        String jsonConfig = FileUtils.readFileToString(new File(noticeSrc), StandardCharsets.UTF_8.name());
        List<String> imageUrls = JsonHelper.toList(jsonConfig);
        LocalCacheHelper.put(TAG, JsonHelper.toJSONString(imageUrls));
        return imageUrls;
    }

    /**
     * faster than Collections.shuffle()
     */
    private void shuffle(List<String> list) {
        Random random = ThreadLocalRandom.current();
        for (int i = list.size() - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            list.set(i, list.set(j, list.get(i)));
        }
    }
}
